'use strict';

const User = require('../model/user');
const logger = require('../lib/logger').logger;

exports.list = function * () {
  let qs = this.query || {};
  logger.info('qs:', qs);
  let options = this.query.options || {};
  let result = yield User.find(qs.query, qs.options);
  this.body = result;
};

exports.find = function * () {
  logger.info('id:', this.params);
  let result = yield User.find({phone: this.params.id});
  this.body = result;
};

exports.create = function * () {
  logger.info('into create users');
  let _user = this.request.body;
  logger.info('_user:', _user)
  let result = yield User.create(_user);
  this.status = 201;
  this.body = result;
};

exports.update = function * () {
  let id = this.params.id;
  let doc = this.request.body;
  // 禁止 email 修改
  if (doc.email) delete doc.email;
  let result = yield User.updateByIdAndReturnNewDoc(id, doc);
  logger.info('update result:', result);
  this.status = 201;
  this.body = result;
};

exports.remove = function * () {
  let id = this.params.id;
  try {
    yield User.findByIdAndRemove(id).exec();
  } catch (e) {
    this.throw(400, e);
  }
  this.status = 204;
};
